var net = require('net');

var port = 15000;
var host = '127.0.0.1';
var mode = 'SERVER';
var conn = null;

conn = net.createServer(function(socket) {
	console.log('client is connected');
	

	socket.on('data', function(data) {
		console.log('- Rcvd '+data);
		if(data.length > 4) {
			//setTimeout(sendEvent(jsonObj, socket),60000);
		}
		});
	socket.on('close', function() {
		console.log('connection closed');
		});
	socket.on('error', function(err) {
		console.log(err);
		});
	
	var jsonObj = {			
			'params': {
				'message': 'welcome to dubai'}};
	//console.log('data: '+JSON.stringify(jsonObj));
	
	//for(var i=1; i<2; i++) {
	setTimeout(sendEvent(jsonObj, socket),10000);
	//}
	
	
});
conn.listen(port,  function(pObj) {				
	console.log('server started listening on port:'+port);
});

function sendEvent(msgObj, socket) {

	if(socket) {
		var data = JSON.stringify(msgObj);
		var msgBuff = new Buffer(4 + data.length);

		msgBuff.writeUInt32BE(msgBuff.length, 0);
		msgBuff.write(data, 4);	
		//socket.write(msgBuff);
		socket.write(msgBuff.slice(0,4));
		socket.write(msgBuff.slice(4));
		console.log("packet sent length = " + msgBuff.length);		
		
		
	}

};